package com.aooci.ordercat.desktop.view;

import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ResourceBundle;

import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.input.InputEvent;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Modality;
import javafx.stage.Stage;

import org.controlsfx.control.action.Action;
import org.controlsfx.dialog.Dialog;
import org.controlsfx.dialog.Dialogs;

import com.aooci.ordercat.desktop.OrdercatMain;
import com.aooci.ordercat.desktop.SystemConstant;
import com.aooci.ordercat.domain.ItemCategory;
import com.aooci.ordercat.enums.OrderStatus;
import com.aooci.ordercat.enums.OrderType;
import com.aooci.ordercat.vo.CheckoutVo;
import com.aooci.ordercat.vo.ItemVo;
import com.aooci.ordercat.vo.OperatedOrderVo;
import com.aooci.ordercat.vo.OrderedItemVo;
import com.aooci.ordercat.vo.TakeawayVo;

@SuppressWarnings({ "restriction", "deprecation" })
public class OrderOperationController implements Initializable {
	
	private OrdercatMain ordercatMain;
	private Stage stage;
	private OperatedOrderVo operatedOrderVo;
	private CheckoutVo checkoutVo;
	private TableView<TakeawayVo> takeawayTable;
	
	private static SimpleDateFormat timeFormat = new SimpleDateFormat("dd/MM/yyyy - HH:mm");
	
	@FXML
	private AnchorPane categoryPane;
	
	// Item table
    @FXML private TableView<ItemVo> itemTable;
    @FXML private TableColumn<ItemVo, String> itemLabelColumn;
    @FXML private TableColumn<ItemVo, String> itemNameColumn;
    @FXML private TableColumn<ItemVo, String> itemPriceColumn;
    private ItemVo selectedItemVo;
    
	// Ordered item table
    @FXML private TableView<OrderedItemVo> orderedItemTable;
    @FXML private TableColumn<OrderedItemVo, Number> orderedItemSortGroupColumn;
    @FXML private TableColumn<OrderedItemVo, String> orderedItemLabelColumn;
    @FXML private TableColumn<OrderedItemVo, String> orderedItemNameColumn;
    @FXML private TableColumn<OrderedItemVo, Number> orderedItemQuantityColumn;
    @FXML private TableColumn<OrderedItemVo, Number> orderedItemPriceColumn;
    @FXML private TableColumn<OrderedItemVo, Number> orderedItemAmountColumn;
    private OrderedItemVo selectedOrderedItemVo;
    
    // Info bar
    @FXML private Label takeawayNumberLabel;
    @FXML private Label takeawayNumber;
    
    @FXML private Label takingTimeLabel;
    @FXML private Label takingTime;
    
    @FXML private Label tableNumberLabel;
    @FXML private Label tableNumber;
    
    @FXML private Label nofClientLabel;
    @FXML private Label nofClient;
    
    @FXML private Label discountRateLabel;
    @FXML private Label discountRate;
    
    @FXML private Label creationTimeLabel;
    @FXML private Label creationTime;
    
    @FXML private Label discountAmountLabel;
    @FXML private Label discountAmount;
    
    @FXML private Label originalTotalLabel;
    @FXML private Label originalTotal;
    
    @FXML private Label totalToPayLabel;
    @FXML private Label totalToPay;
    
    // Order action buttons
    @FXML private Button backButton;
    @FXML private Button checkoutButton;
    @FXML private Button clearButton;
    @FXML private Button changeTableButton;
    @FXML private Button discardButton;
	@FXML private Button sendAllButton;
	@FXML private Button sendNewButton;
	@FXML private Button reopenButton;
	
	// Ordered item aciton buttons
	@FXML private Button removeButton;
	@FXML private Button plusButton;
	@FXML private Button minusButton;
	@FXML private Button upButton;
	@FXML private Button downButton;
	
    @FXML private TextField remark;

    // Ordered item operations


	
	public void initialize(URL arg0, ResourceBundle arg1) {
    	// Initialize the item table.
		itemLabelColumn.setCellValueFactory(cellData -> cellData.getValue().labelProperty());
		itemNameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
		itemPriceColumn.setCellValueFactory(cellData -> cellData.getValue().priceProperty());
		
        // Listen for selection changes and show the person details when changed.
		itemTable.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> setSelectedItemVo(newValue));
		
    	// Initialize the item table.
		orderedItemSortGroupColumn.setCellValueFactory(cellData -> cellData.getValue().sortGroupProperty());
		orderedItemLabelColumn.setCellValueFactory(cellData -> cellData.getValue().labelProperty());
		orderedItemNameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
		orderedItemQuantityColumn.setCellValueFactory(cellData -> cellData.getValue().quantityProperty());
		orderedItemPriceColumn.setCellValueFactory(cellData -> cellData.getValue().priceProperty());
		orderedItemAmountColumn.setCellValueFactory(cellData -> cellData.getValue().amountProperty());
		orderedItemTable.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> setSelectedOrderedItemVo(newValue));
		
		
		this.backButton.setOnAction((event) -> {
			((Stage) this.backButton.getScene().getWindow()).close();
		});
		
		this.itemTable.getStyleClass().add("item_list");
		this.itemTable.setFixedCellSize(40.0);
		this.orderedItemTable.getStyleClass().add("item_list");
		this.orderedItemTable.setFixedCellSize(40.0);
		
	}
	
	public void init(OrdercatMain ordercatMain, Stage stage, OperatedOrderVo operatedOrderVo, TableView<TakeawayVo> takeawayTable){
		this.ordercatMain = ordercatMain;
		this.stage = stage;
		this.operatedOrderVo = operatedOrderVo;
		this.checkoutVo = this.ordercatMain.getOrderOperationService().loadCheckoutVo(this.operatedOrderVo.getOrdercat().getId());
		this.takeawayTable = takeawayTable;
		//Item category button list
		int lx = 10;
		int ly = 10;
		for(ItemCategory category : this.ordercatMain.getCategories()){
			Button button = new Button();
			button.setText(category.getLabel());
			button.setFont(Font.font ("System", 12));
			button.setPrefWidth(60);
			button.setPrefHeight(40);
			button.setLayoutX(lx);
			button.setLayoutY(ly);
			button.setOnAction(new EventHandler<ActionEvent>() {
			    @Override public void handle(ActionEvent e) {
			    	itemTable.setItems(FXCollections.observableArrayList(ordercatMain.getItems().get(category.getId())));
			    }
			});
			
			if(lx < 70){
				lx += 65;
			}else{
				lx = 10;
				ly += 45;
			}
			this.categoryPane.getChildren().add(button);
		}
		
		if(OrderType.TAKEAWAY.equals(this.operatedOrderVo.getOrdercat().getType())){
			this.tableNumberLabel.setVisible(false);
			this.tableNumber.setVisible(false);
			this.changeTableButton.setVisible(false);
			
			this.takeawayNumber.setText(String.valueOf(this.operatedOrderVo.getTakeaway().getId()));
			
		}else if(OrderType.DINING_HALL.equals(this.operatedOrderVo.getOrdercat().getType())){
			this.takeawayNumberLabel.setVisible(false);
			this.takeawayNumber.setVisible(false);
			this.takingTimeLabel.setVisible(false);
			this.takingTime.setVisible(false);
			
			this.tableNumber.setText(this.operatedOrderVo.getDiningTable().getLabel());
			
		}
		this.creationTime.setText(timeFormat.format(this.operatedOrderVo.getOrdercat().getCreationTimestamp().getTime()));
		this.takingTime.setText(timeFormat.format(this.operatedOrderVo.getOrdercat().getCreationTimestamp().getTime()));
		this.discountAmount.setText(String.valueOf(this.checkoutVo.getDiscount()));
		this.discountRate.setText(String.valueOf(this.checkoutVo.getDiscountRate()));
		this.originalTotal.setText(String.valueOf(this.operatedOrderVo.getOrdercat().getTotal()));
		this.totalToPay.setText(String.valueOf(this.checkoutVo.getTotalToPay()));
		
//		SortedList sortedList = new SortedList(FXCollections.observableArrayList(this.ordercatMain.getOrderOperationService().loadOrderedItems(this.currentOrdercat.getId())));
//		this.orderedItemTable.setItems(sortedList);
//		sortedList.comparatorProperty().bind(this.orderedItemTable.comparatorProperty());
//		
		this.orderedItemTable.setItems(FXCollections.observableArrayList(this.ordercatMain.getOrderOperationService().loadOrderedItems(this.operatedOrderVo.getOrdercat().getId())));
		for(OrderedItemVo vo:this.orderedItemTable.getItems()){
			if((vo.getRemark() != null) && !vo.getRemark().isEmpty())
				vo.setName("(" +vo.getRemark()+ ") " + vo.getName());
		}
		this.updateActionButtonsStatus();
		
		this.orderedItemTable.getSortOrder().add(this.orderedItemSortGroupColumn);
		this.orderedItemTable.getSortOrder().add(this.orderedItemLabelColumn);
		
		if(OrderStatus.PAID.equals(this.operatedOrderVo.getOrdercat().getStatus())){
			this.changeOperationsEditable(false);
		}
	}
	
	public void clearOrder(){

		try {
			FXMLLoader loader = new FXMLLoader();
			loader.setLocation(OrdercatMain.class.getResource(SystemConstant.CLEAR_ORDER_FXML));
			VBox page = (VBox) loader.load();

			Stage dialogStage = new Stage();
			//dialogStage.initStyle(StageStyle.DECORATED);
			dialogStage.setTitle(SystemConstant.CLEAR_ORDER_TITLE);
			dialogStage.initModality(Modality.WINDOW_MODAL);
			dialogStage.initOwner(this.ordercatMain.getPrimaryStage());
			dialogStage.setResizable(true);
			dialogStage.setFocused(true);
			
			Scene scene = new Scene(page);
			dialogStage.setScene(scene);

			ClearOrderController controller = loader.getController();
			controller.init(ordercatMain, operatedOrderVo, checkoutVo);
			dialogStage.showAndWait();
			
				((Stage) this.backButton.getScene().getWindow()).close();
				this.ordercatMain.getDiningHallTables().get(this.operatedOrderVo.getDiningTable().getId()).getStyleClass().remove("dininghall_paid_table");
				this.ordercatMain.getDiningHallTables().get(this.operatedOrderVo.getDiningTable().getId()).getStyleClass().add("dininghall_free_table");
				this.operatedOrderVo = null;
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void updateActionButtonsStatus(){
		if(this.orderedItemTable.getItems().size() > 0){
			this.checkoutButton.setDisable(false);
			this.sendAllButton.setDisable(false);
			this.sendNewButton.setDisable(false);
			this.removeButton.setDisable(false);
			this.plusButton.setDisable(false);
			this.minusButton.setDisable(false);
			this.upButton.setDisable(false);
			this.downButton.setDisable(false);
		}else{
			this.checkoutButton.setDisable(true);
			this.sendAllButton.setDisable(true);
			this.sendNewButton.setDisable(true);
			this.removeButton.setDisable(true);
			this.plusButton.setDisable(true);
			this.minusButton.setDisable(true);
			this.upButton.setDisable(true);
			this.downButton.setDisable(true);
		}
	}
	
	@FXML
	public void checkout(){
		Action response = Dialogs.create()
		        .owner(this.stage)
		        .title("Check out")
		        .masthead("Check out current order?")
		        .message("Do you want to continue?")
		        .showConfirm();

		if (Dialog.ACTION_YES.equals(response)) {
			this.ordercatMain.getOrderOperationService().checkout(this.operatedOrderVo);
			this.ordercatMain.getPrintingService().printReceiptToClient(operatedOrderVo);
			this.changeOperationsEditable(false);
			this.ordercatMain.getDiningHallTables().get(this.operatedOrderVo.getDiningTable().getId()).getStyleClass().remove("dininghall_occupied_table");
			this.ordercatMain.getDiningHallTables().get(this.operatedOrderVo.getDiningTable().getId()).getStyleClass().add("dininghall_paid_table");
		} 
	}
	
    public void reopenOrder(){
		Action response = Dialogs.create()
		        .owner(this.stage)
		        .title("Reopen Order")
		        .masthead("Reopen current order?")
		        .message("Do you want to continue?")
		        .showConfirm();

		if (Dialog.ACTION_YES.equals(response)) {
	    	this.ordercatMain.getOrderOperationService().reopenOrder(this.operatedOrderVo);
	    	this.changeOperationsEditable(true);
	    	this.ordercatMain.getDiningHallTables().get(this.operatedOrderVo.getDiningTable().getId()).getStyleClass().remove("dininghall_paid_table");
	    	this.ordercatMain.getDiningHallTables().get(this.operatedOrderVo.getDiningTable().getId()).getStyleClass().add("dininghall_occupied_table");
		} 
    }
	
	private void changeOperationsEditable(boolean editable){
		this.checkoutButton.setVisible(editable);
		this.sendAllButton.setVisible(editable);
		this.sendNewButton.setVisible(editable);
		this.changeTableButton.setDisable(!editable);
		this.discardButton.setDisable(!editable);
		this.clearButton.setVisible(!editable);
		this.reopenButton.setVisible(!editable);
		
		this.itemTable.setDisable(!editable);
		this.orderedItemTable.setDisable(!editable);
		this.remark.setDisable(!editable);
		
		this.removeButton.setDisable(!editable);
		this.plusButton.setDisable(!editable);
		this.minusButton.setDisable(!editable);
		this.upButton.setDisable(!editable);
		this.downButton.setDisable(!editable);
	}
	
	@FXML
	private void focusOrderedItemTable(){
		if(this.orderedItemTable.getItems().size() > 0){
			this.removeButton.setDisable(false);
			this.plusButton.setDisable(false);
			this.minusButton.setDisable(false);
			this.upButton.setDisable(false);
			this.downButton.setDisable(false);
		}
	}
	
	@FXML
	private void exitOrderedItemTable(){
		this.removeButton.setDisable(true);
		this.plusButton.setDisable(true);
		this.minusButton.setDisable(true);
		this.upButton.setDisable(true);
		this.downButton.setDisable(true);
	}
	
	@FXML
	public void printToKitchen(){
		this.ordercatMain.getPrintingService().printToKitchen(operatedOrderVo);
		Dialogs.create().lightweight()
		        .owner(this.stage)
		        .title("Confirmation")
		        .message("Order has sent!").showInformation();
	}
	
	@FXML
	public void printAddingToKitchen(){
		this.ordercatMain.getPrintingService().printAddingToKitchen(operatedOrderVo);
		Dialogs.create().lightweight()
        .owner(this.stage)
        .title("Confirmation")
        .message("Order has sent!").showInformation();
	}
	
	@FXML
	private void discardOrder(){
		Action response = Dialogs.create()
		        .owner(this.stage)
		        .title("Confirmation")
		        .masthead("Discarding Order?")
		        .message("Do you want to continue?")
		        .showConfirm();

		if (Dialog.ACTION_YES.equals(response)) {
			if(OrderType.DINING_HALL.equals(this.operatedOrderVo.getOrdercat().getType())){
				this.ordercatMain.getOrderOperationService().discardDiningTableOrder(this.operatedOrderVo.getDiningTable().getId());
				if(OrderStatus.SERVICING.equals(this.operatedOrderVo.getOrdercat().getStatus())){
					this.ordercatMain.getDiningHallTables().get(this.operatedOrderVo.getDiningTable().getId()).getStyleClass().remove("dininghall_occupied_table");
				}else if(OrderStatus.PAID.equals(this.operatedOrderVo.getOrdercat().getStatus())){
					this.ordercatMain.getDiningHallTables().get(this.operatedOrderVo.getDiningTable().getId()).getStyleClass().remove("dininghall_paid_table");
				}
				this.ordercatMain.getDiningHallTables().get(this.operatedOrderVo.getDiningTable().getId()).getStyleClass().add("dininghall_free_table");
				
			}else if(OrderType.TAKEAWAY.equals(this.operatedOrderVo.getOrdercat().getType())){
				this.ordercatMain.getOrderOperationService().discardTakeawayOrder(this.takeawayTable.getSelectionModel().getSelectedItem().getId());
				this.takeawayTable.getItems().remove(this.takeawayTable.getSelectionModel().getSelectedItem());
				//this.takeawayButtons.getSelectionModel().clearSelection();
			}
			this.stage.close();
		} 
	}
	
	@FXML
	private void removeOrderedItem(){
		this.ordercatMain.getOrderOperationService().disorderItem(this.operatedOrderVo, this.selectedOrderedItemVo.getEntityId());
		this.ordercatMain.getOrderOperationService().updateCheckoutVo(this.checkoutVo, this.operatedOrderVo);
		this.checkoutVo = this.ordercatMain.getOrderOperationService().loadCheckoutVo(this.operatedOrderVo.getOrdercat().getId());
		this.updateInfoDisplay();
		this.orderedItemTable.getItems().remove(this.selectedOrderedItemVo);
		this.orderedItemTable.sort();
		this.updateActionButtonsStatus();
	}
	
	@FXML
	private void updateItemRemark(final InputEvent event) {
		if (event instanceof KeyEvent) {
			final KeyEvent keyEvent = (KeyEvent) event;
			if (keyEvent.getCode() == KeyCode.ENTER) {
				selectedOrderedItemVo.setName(selectedOrderedItemVo.getName().replaceAll(".*\\) ", ""));
				selectedOrderedItemVo.setRemark(remark.getText());
				if((selectedOrderedItemVo.getRemark() != null) && !selectedOrderedItemVo.getRemark().isEmpty()){
					selectedOrderedItemVo.setName("(" +selectedOrderedItemVo.getRemark()+ ") " + selectedOrderedItemVo.getName());
				}
					
				this.ordercatMain.getOrderOperationService().updateOrderedItem(operatedOrderVo, selectedOrderedItemVo);
//				for (Node n : orderedItemTable.lookupAll("TableRow")) {
//					if (n instanceof TableRow) {
//						TableRow row = (TableRow) n;
//						OrderedItemVo oiv = (OrderedItemVo) row.getItem();
//						if (oiv.equals(selectedOrderedItemVo)) {
//							if (selectedOrderedItemVo.getRemark().isEmpty()) {
//								row.setStyle("-fx-background-color: white;");
//							} else {
//								row.setStyle("-fx-background-color: lemonchiffon;");
//							}
//							break;
//						}
//					}
//				}
			}
		}
	}

	@FXML
	private void upOrderedItem(){
		int position = this.orderedItemTable.getItems().indexOf(this.selectedOrderedItemVo);
		if(position > 0){
			this.orderedItemTable.getItems().add(position-1, this.selectedOrderedItemVo);
			this.orderedItemTable.getItems().remove(position+1);
			this.orderedItemTable.getSelectionModel().select(position-1);
		}
	}
	
	@FXML
	private void downOrderedItem(){
		int position = this.orderedItemTable.getItems().indexOf(this.selectedOrderedItemVo);
		if(position < this.orderedItemTable.getItems().size()-1){
			this.orderedItemTable.getItems().add(position+2, this.selectedOrderedItemVo);
			this.orderedItemTable.getItems().remove(position);
			this.orderedItemTable.getSelectionModel().select(position+1);
		}
	}
	
	@FXML
	private void modifyOrderedItemQuantityByKey(final InputEvent event) {
		if (event instanceof KeyEvent) {
			final KeyEvent keyEvent = (KeyEvent) event;
			if((keyEvent.getCode() == KeyCode.PLUS) || (keyEvent.isShiftDown() && keyEvent.getCode() == KeyCode.EQUALS)) {
				this.plusOrderedItem();
			}else if (keyEvent.getCode() == KeyCode.MINUS) {
				this.minusOrderedItem();
			}else if (keyEvent.getCode() == KeyCode.DELETE) {
				this.removeOrderedItem();;
			}
		}
	}
	
	@FXML
	private void plusOrderedItem(){
		this.selectedOrderedItemVo.setQuantity(this.selectedOrderedItemVo.getQuantity()+1);
		OrderedItemVo updatedOrderedItemVo = this.ordercatMain.getOrderOperationService().updateOrderedItem(operatedOrderVo, this.selectedOrderedItemVo);
		this.selectedOrderedItemVo.setAmount(updatedOrderedItemVo.getAmount());
		this.ordercatMain.getOrderOperationService().updateCheckoutVo(this.checkoutVo, this.operatedOrderVo);
		this.checkoutVo = this.ordercatMain.getOrderOperationService().loadCheckoutVo(this.operatedOrderVo.getOrdercat().getId());
		this.updateInfoDisplay();
	}
	
	@FXML
	private void minusOrderedItem(){
		if(this.selectedOrderedItemVo.getQuantity() > 1){
			this.selectedOrderedItemVo.setQuantity(this.selectedOrderedItemVo.getQuantity()-1);
			OrderedItemVo updatedOrderedItemVo = this.ordercatMain.getOrderOperationService().updateOrderedItem(operatedOrderVo, this.selectedOrderedItemVo);
			this.selectedOrderedItemVo.setAmount(updatedOrderedItemVo.getAmount());
			this.ordercatMain.getOrderOperationService().updateCheckoutVo(this.checkoutVo, this.operatedOrderVo);
			this.checkoutVo = this.ordercatMain.getOrderOperationService().loadCheckoutVo(this.operatedOrderVo.getOrdercat().getId());
			this.updateInfoDisplay();
		}
	}

	@FXML
	private void itemTableDoubleClicked(MouseEvent mouseEvent) {
		if (mouseEvent.getButton().equals(MouseButton.PRIMARY)) {
			if (mouseEvent.getClickCount() > 1) {
				//System.out.println("Double clicked A_button"+ selectedItemVo.getName());
				this.orderItem();
			}
		}
	}

	@FXML
	private void selectItemByKey(final InputEvent event) {
		if (event instanceof KeyEvent) {
			final KeyEvent keyEvent = (KeyEvent) event;
			if((keyEvent.getCode() == KeyCode.PLUS) || (keyEvent.isShiftDown() && keyEvent.getCode() == KeyCode.EQUALS)) {
				System.out.println("PLUS = " + selectedItemVo.getName());
				this.orderItem();
			}else if (keyEvent.getCode() == KeyCode.MINUS) {
				System.out.println("MINUS = " + selectedItemVo.getName());
				this.disorderOneSelectedItem();
			}
		}
	}
	
	private void orderItem(){
        OrderedItemVo orderedItemVo = this.ordercatMain.getOrderOperationService().orderItem(this.operatedOrderVo, this.selectedItemVo);

		if(selectedOrderedItemVo != null){
			this.selectedOrderedItemVo.setQuantity(orderedItemVo.getQuantity());
			this.selectedOrderedItemVo.setAmount(orderedItemVo.getAmount());
		}else{
			this.selectedOrderedItemVo = orderedItemVo;
			this.orderedItemTable.getItems().add(orderedItemVo);
			this.orderedItemTable.sort();
		}
		this.updateInfoDisplay();
		this.updateActionButtonsStatus();
		this.ordercatMain.getOrderOperationService().updateCheckoutVo(this.checkoutVo, this.operatedOrderVo);
        this.checkoutVo = this.ordercatMain.getOrderOperationService().loadCheckoutVo(this.operatedOrderVo.getOrdercat().getId());
		
	}
	
	private void updateInfoDisplay(){
		this.discountAmount.setText(String.valueOf(this.checkoutVo.getDiscount()));
		this.discountRate.setText(String.valueOf(this.checkoutVo.getDiscountRate()));
		this.originalTotal.setText(String.valueOf(this.operatedOrderVo.getOrdercat().getTotal()));
		this.totalToPay.setText(String.valueOf(this.checkoutVo.getTotalToPay()));
	}
	
	private void disorderOneSelectedItem(){
		if(this.selectedOrderedItemVo != null){
			this.minusOrderedItem();
		}
	}
	
	@FXML
	public void changeTable(){
		try {
			FXMLLoader loader = new FXMLLoader();
			loader.setLocation(OrdercatMain.class.getResource(SystemConstant.CHANGE_TABLE_FXML));
			AnchorPane page = (AnchorPane) loader.load();

			Stage dialogStage = new Stage();
			//dialogStage.initStyle(StageStyle.DECORATED);
			dialogStage.setTitle(SystemConstant.CHANGE_TABLE_TITLE);
			dialogStage.initModality(Modality.WINDOW_MODAL);
			dialogStage.initOwner(this.ordercatMain.getPrimaryStage());
			dialogStage.setResizable(true);
			dialogStage.setFocused(true);
			
			Scene scene = new Scene(page);
			dialogStage.setScene(scene);

			ChangeTableController controller = loader.getController();
			controller.init(ordercatMain, page, operatedOrderVo, this.tableNumber);
			dialogStage.showAndWait();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}


	public void setSelectedItemVo(ItemVo selectedItemVo) {
		this.selectedItemVo = selectedItemVo;
		this.selectedOrderedItemVo = null;
		if(this.selectedItemVo != null){
			for(OrderedItemVo obj: this.orderedItemTable.getItems()){
				if(obj.getItem().getId().equals(this.selectedItemVo.getId()) && ((null == obj.getRemark()) || obj.getRemark().isEmpty())){
					this.selectedOrderedItemVo = obj;
					break;
				}
			}
		}
	}
	public void setSelectedOrderedItemVo(OrderedItemVo selectedOrderedItemVo) {
		this.selectedOrderedItemVo = selectedOrderedItemVo;
		if(this.selectedOrderedItemVo != null)
			this.remark.setText(this.selectedOrderedItemVo.getRemark());
	}

}
